import os
import configparser
from collections import defaultdict
import json
from datetime import datetime,timedelta
import re

DIZHI=['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥']
TIANGAN=['甲','乙','丙','丁','戊','己','庚','辛','壬','癸']
LIUQI=['厥阴风木','少阴君火','太阴湿土','少阳相火','阳明燥金','太阳寒水']  #先三阴，后三阳
BASE_LIUQI=['厥阴风木','少阴君火','少阳相火','太阴湿土','阳明燥金','太阳寒水'] #一年中六段，每段73天，固定不变
SITIAN={
    '子':['少阴君火','阳明燥金'],
    '丑':['太阴湿土','太阳寒水'],
    '寅':['少阳相火','厥阴风木'],
    '卯':['阳明燥金','少阴君火'],
    '辰':['太阳寒水','太阴湿土'],
    '巳':['厥阴风木','少阳相火'],
    '午':['少阴君火','阳明燥金'],
    '未':['太阴湿土','太阳寒水'],
    '申':['少阳相火','厥阴风木'],
    '酉':['阳明燥金','少阴君火'],
    '戌':['太阳寒水','太阴湿土'],
    '亥':['厥阴风木','少阳相火']
}
WUYUN={
  "甲": ["太宫土运", "土运太过"],
  "乙": ["少商金运", "金运不及"],
  "丙": ["太羽水运", "水运太过"],
  "丁": ["少角木运", "木运不及"],
  "戊": ["太徵火运", "火运太过"],
  "己": ["少宫土运", "土运不及"],
  "庚": ["太商金运", "金运太过"],
  "辛": ["少羽水运", "水运不及"],
  "壬": ["太角木运", "木运太过"],
  "癸": ["少徵火运", "火运不及"]
}

LIUQI_STAGE={
    '初之气':{'主气':'厥阴风木','节气':['大寒','立春','雨水','惊蛰']},
    '二之气':{'主气':'少阴君火','节气':['春分','清明','谷雨','立夏']},
    '三之气':{'主气':'少阳相火','节气':['小满','芒种','夏至','小暑']},
    '四之气':{'主气':'太阴湿土','节气':['大暑','立秋','处暑','白露']},
    '五之气':{'主气':'阳明燥金','节气':['秋分','寒露','霜降','立冬']},
    '终之气':{'主气':'太阳寒水','节气':['小雪','大雪','冬至','小寒']}
}

# 基础设置
config = configparser.ConfigParser()
config.read('config.cfg',encoding='utf-8')


class wuYunLiuQi():
    def __init__(self):
        with open(r'1800-2100jieqi.json','r',encoding='utf-8') as f:
            self.JIEQI=json.load(f)
    
    def get_tizhi(self,year):
        gz=self._get_year_gz(int(year))
        gz_str=gz['gan']+gz['zhi']
        
        wuyun_liuqi_tizhi_json=config['Files']['wuyun_liuqi_tizhi_json']
        with open(wuyun_liuqi_tizhi_json,'r',encoding='utf-8') as f:
            TIZHI=json.load(f)
        birth_tizhi=TIZHI[gz_str]

        # 获取当年的五运六气信息
        wylq_info=self.get_keqi_order_from_year(year=year)
        birth_wylq={
            'keyun':wylq_info['keyun2'],
            'sitian':wylq_info['sitian'],
            'zaiquan':wylq_info['zaiquan']
        }


        return {'year':year,'ganzhi':gz_str,'birth_wylq':birth_wylq,'birth_tizhi':birth_tizhi}
    
    def get_wuyun_liuqi_advice(self,year):
        analysis_res=self.get_keqi_order_from_year(year)

        wylq_completed_30_json=config['Files']['wylq_completed_30_json']
        with open (wylq_completed_30_json,'r',encoding='utf-8') as f:
            wylq_data=json.load(f)
        
        health_advice=wylq_data[analysis_res['id']]

        return {'year_result':analysis_res,'health_advice':health_advice}


    def get_liuqi_stage(self,year):
        jieqi=self.JIEQI[str(year)]
        jieqi_next_year=self.JIEQI[str(int(year)+1)]
        stage_names=list(LIUQI_STAGE.keys())
        key_stages=['大寒','春分','小满','大暑','秋分','小雪']
        pattern = r"\d{4}年\d{1,2}月\d{1,2}日"
        this_year_stages={}
        for n,stage in enumerate(key_stages):      
            prd=[]      
            date_str=datetime.strptime(re.findall(pattern,jieqi[stage])[0],'%Y年%m月%d日').strftime('%Y年%m月%d日')
            
            
            if n<5:
                next_jieqi_date_str_previous=(datetime.strptime(re.findall(pattern,jieqi[key_stages[n+1]])[0],'%Y年%m月%d日')-timedelta(days=1)).strftime('%Y年%m月%d日')
                this_year_stages[stage_names[n]]=[date_str,next_jieqi_date_str_previous]
            else:
                next_year_dahan_previous=(datetime.strptime(re.findall(pattern,jieqi_next_year['大寒'])[0],'%Y年%m月%d日')-timedelta(days=1)).strftime('%Y年%m月%d日')
                this_year_stages[stage_names[n]]=[date_str,next_year_dahan_previous]

                
        return {'year':year,'liuqi_stages':this_year_stages}

    def get_keqi_order_from_year(self,year=2025):
        gz=self._get_year_gz(year)
        # 五运
        keyun,keyun2=WUYUN[gz['gan']]
        # 司天、在泉
        st=SITIAN[gz['zhi']][0]
        zq=SITIAN[gz['zhi']][1]

        # 本年的客气顺序
        this_year_keqi_order=self._reorder_liuqi(third_keqi=st)
        # print(f'{year}{gz['gan']}{gz['zhi']}年，司天:{st},在泉：{zq}，客气顺序：{this_year_keqi}')

        # 本年的主运、客气日期
        this_year_stages=self.get_liuqi_stage(year=year)

        return {
            'year':year,
            'tg':gz['gan'],
            'dz':gz['zhi'],
            'keyun':keyun,
            'keyun2':keyun2,
            'sitian':st,
            'zaiquan':zq,
            'this_year_keqi_order':this_year_keqi_order,
            'this_year_stages':this_year_stages,
            'id':f'{keyun}-{st}-{zq}',
        }


    def _reorder_liuqi(self,third_keqi):
        # 找到目标元素的索引
        target_index = LIUQI.index(third_keqi)
        # 计算需要向左移动的步数，使得目标元素成为第3位（索引2）
        shift = (target_index - 2) % 6
        # 重新排列列表
        reordered = LIUQI[shift:] + LIUQI[:shift]
        return reordered

    
    def _get_zaiquan_from_sitian(self,st):
        LIUQI_ORDER=['太阳寒水','厥阴风木','少阴君火','太阴湿土','少阳相火','阳明燥金']   
        order=LIUQI_ORDER.index(st)
        if order<3:
            return LIUQI_ORDER[order+3]
        else:
            return LIUQI_ORDER[order-3]
    

    def _get_year_gz(self,year=2025):
        year=int(year)
        gan=TIANGAN[(year-4)%10]
        zhi=DIZHI[(year-4)%12]
        
        return {'gan':gan,'zhi':zhi}
    

    def generate_templates(self,s=1984,e=1985):
        wylq_dict=Vividict()
        for i in range(s,e):
            res=self.get_keqi_order_from_year(i)
            # 客气-司天-在泉 组合成的id
            keqi_id=res['id']
            wylq_dict[keqi_id]['客气顺序']=res['this_year_keqi_order']
            for n in range(6):
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['主气']=BASE_LIUQI[n]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['客气']=res['this_year_keqi_order'][n]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['气候特征']=[]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['调养方案']['饮食']=[]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['调养方案']['起居']=[]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['调养方案']['情志']=[]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['保健穴位']=[{'名称':'','功效':''}]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['禁忌']=[]
                wylq_dict[keqi_id]['分段详情'][list(LIUQI_STAGE.keys())[n]]['经典参考']=[]

        return wylq_dict


    

class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value


if __name__=='__main__':
    p=wuYunLiuQi()
    # res=p.get_keqi_order_from_year(2015)
    
    # print(res)

    # 当年五运六气
    # res=p.get_wuyun_liuqi_advice(year=2025)
    # print(res)

    # 出生体质
    res=p.get_tizhi(year=2025)
    print(res)

    # 生成模板文件
    # res=p.generate_templates(1984,2025)
    # # print(res)
    # with open(r'/media/jack/data/py/flask_bazi/static/wylq_config/wylq_template.json','w',encoding='utf-8') as f:
    #     json.dump(res,f,ensure_ascii=False,indent=4)  
    # with open(r'/media/jack/data/py/flask_bazi/static/wylq_config/wylq_template.json','r',encoding='utf-8') as f:
        # fn=json.load(f)
        
    # print(len(fn.keys()))
